package net.lesscoding.server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.lesscoding.message.ChatRequestMessage;
import net.lesscoding.message.ChatResponseMessage;
import net.lesscoding.session.SessionFactory;

/**
 * @author eleven
 * @date 2024/10/31 16:04
 * @apiNote
 */
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        String msgTo = msg.getTo();
        Channel toChannel = SessionFactory.session().getChannel(msgTo);
        // 客户端在线
        if (toChannel != null) {
            toChannel.writeAndFlush(new ChatResponseMessage(msg.getForm(), msg.getContent()));
        } else {
            // 客户端离线
            ctx.writeAndFlush(new ChatResponseMessage(false, msgTo + "不在线"));
        }
    }
}
